package com.twotiger.and.activity.project.debt;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.project.ProjectDetailPage;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.DebtProjectdetailData;
import com.twotiger.and.bean.Interest;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.bean.UserBanklist;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.URLUtil;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

/**
 * 转让项目-输入金额
 * @Description: TODO(这里描述这个类的作用) 
 * @Author gao
 * @Date 2015年8月12日 下午2:50:58
 */
public class DebtInverstInputAmountPage extends BaseActivity implements OnClickListener {
    private static final int GETASSERTSUCCES = 0;
    private static final int GETASSERTFAIL = 1;
    private static final int COUNTINVERSTSUCCES = 2;
    private static final int COUNTINVERSTFAIL = 3;
    private static final int COUNTINVERSTBYACCOUNTAMOUNTSUCCES = 4;
    private static final int COUNTINVERSTBYACCOUNTAMOUNTFAIL = 5;
    private static final int LOOPTOCOUNTINSERT = 6;

    private ImageView sub_title_left_bt;
    private TextView sub_title_center_tv;
    private TextView can_inverst_text;
    private EditText input_amount_edit;
    private TextView expect_income;
    private Button inverst_btn;
    private HashMap<String, String> parm;
    private View input_inverst_ll;
    private double avlibe; //剩余可买本金
    private Interest interest;
    private DebtProjectdetailData order;
    private UserBanklist cunbanklist;
    private TextView sub_title_right_tv;
    private String amountContent; //金额输入框的内容

    private String tempNumNow;
    private double minInvestAmount; //最小投资额    为0表示无限制
    private double maxInvestAmount; //最大投资额    为0表示无限制

    private Button all_enter_btn;
    private UserAsset userAsset;
    private boolean allBuy;  //是否全买

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.input_debt_inverst_amount_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        sub_title_left_bt = (ImageView) view.findViewById(R.id.sub_title_left_bt);
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        sub_title_right_tv = (TextView) view.findViewById(R.id.sub_title_right_tv);
        can_inverst_text = (TextView) view.findViewById(R.id.can_inverst_text);
        input_amount_edit = (EditText) view.findViewById(R.id.input_amount_edit);
        expect_income = (TextView) view.findViewById(R.id.expect_income);
        inverst_btn = (Button) view.findViewById(R.id.inverst_btn);
        input_inverst_ll = view.findViewById(R.id.input_inverst_ll);
        all_enter_btn = (Button) view.findViewById(R.id.all_enter_btn);

    }

    @Override
    public void onClick(View view) {

        if (view == null) {
            return;
        }

        switch (view.getId()) {
        case R.id.all_enter_btn: //全投
            //需要把余额来请求预期收益接口，得到对应的垫付利息和打折金额,然后按规则跟剩余可买比较
            if (avlibe != 0.00 && userAsset != null) {
                //全投规则：剩余可买本金   跟    可用余额+打折金额-垫付利息，两者取小
                countinsertByAccountAmount(userAsset.avaliable + "");
            }
            break;
        case R.id.sub_title_right_tv:
            Intent in = new Intent(mContext, WebViewPage.class);
            in.putExtra("title", "合同");
            Map<String, String> contractmap = new HashMap<String, String>();
            contractmap.put("pType", order.getpType());
            contractmap.put("token", getToken());
            in.putExtra("url", Constants.HOST + Constants.CONTRACT + "contractDemoHtml?"
                    + URLUtil.createContractUrl(contractmap, "3.0"));
            startNewActivity(in, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.sub_title_left_bt:
            onBackPress();
            break;
        case R.id.inverst_btn:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String amount = input_amount_edit.getText().toString().trim();
            if (StringUtils.isEmpty(amount)) {
                showToast("请输入购买金额");
                return;
            }
            if (minInvestAmount != 0) {
                if (Double.parseDouble(amount) < minInvestAmount) {
                    showToast("起投金额" + ArithUtils.coverMoney(minInvestAmount + "") + "元起");
                    return;
                }
            }
            if (maxInvestAmount != 0) {
                if (Double.parseDouble(amount) > maxInvestAmount) {
                    showToast("最大投资额度为：" + ArithUtils.coverMoney(maxInvestAmount + ""));
                    return;
                }
            }
            if (Double.parseDouble(amount) > avlibe) {
                showToast("剩余可购买本金为：" + ArithUtils.coverMoney(avlibe + ""));
                return;
            }
            if ("预期收益：计算中...".equals(expect_income.getText().toString().trim())) { //如果显示正在计算中，不能到下一步。因为下一个页面要用到预计收益         interest == null
                return;
            }
            if (ArithUtils.sub(avlibe, Double.parseDouble(amount)) > 0
                && ArithUtils.sub(avlibe, Double.parseDouble(amount)) < minInvestAmount) {
                PromptManager.showDebtInvestAlert(DebtInverstInputAmountPage.this,
                    "剩余可购买本金 - 购买金额 >= 最低可投金额(" + minInvestAmount + "元)   \n否则项目将无法完全转让",
                    new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            input_amount_edit.setText("");
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
                return;
            }
            order.setOrderamount(Double.parseDouble(amount)); //投资金额
            order.setExpectinterest(interest.getInterest()); //预计收益
            order.setDfInterest(interest.getDfInterest()); //垫付利息
            order.setAssignAmount(interest.getAssignAmount());//打折金额
            Intent intent = new Intent(mContext, DebtInverstConfirmPage.class).putExtra("ORDER",
                order);
            startNewActivityforresult(intent, R.anim.push_left_in, R.anim.push_left_out,
                ProjectDetailPage.TENDERREQUEST);
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        super.onActivityResult(requestcode, resultcode, intent);
        if (requestcode == ProjectDetailPage.TENDERREQUEST) {
            if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_SUC) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_SUC);
                finish();
            } else if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_FAI) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_FAI);
                finish();
            }
        }
    }

    @Override
    protected void setListener() {

        amountContent = input_amount_edit.getText().toString().trim();

        inverst_btn.setOnClickListener(this);
        sub_title_left_bt.setOnClickListener(this);
        sub_title_right_tv.setOnClickListener(this);
        all_enter_btn.setOnClickListener(this);

        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETASSERTSUCCES: //由于全投按钮是去剩余可投和账户余额的较小值，故此处请求下账户信息接口
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        userAsset = JSONObject.parseObject(result.data, UserAsset.class);

                    } else {
                        showToast(userAsset.codeDesc);
                    }
                    break;
                case GETASSERTFAIL:

                    break;
                case COUNTINVERSTBYACCOUNTAMOUNTSUCCES:
                    Basebean result_2 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_2.isOk()) {
                        interest = JSON.parseObject(result_2.data, Interest.class);
                        double cmopareAmount = interest.getAllAmount();
                        if (avlibe >= cmopareAmount) {//剩余可买大于购买金额
                            input_amount_edit.setText(ArithUtils.coverMoney(cmopareAmount + ""));
                            input_amount_edit.setSelection(ArithUtils
                                .coverMoney(cmopareAmount + "").length());
                        } else {
                            input_amount_edit.setText(ArithUtils.coverMoney(avlibe + ""));//项目可投小于goumai 金额
                            input_amount_edit.setSelection(ArithUtils.coverMoney(avlibe + "")
                                .length());
                        }
                        expect_income.setText("预期收益："
                                + ArithUtils.formatFloatNumber(interest
                                    .getInterest()) + "元");
                    } else {
                        showToast(result_2.codeDesc);
                    }
                    break;
                case COUNTINVERSTBYACCOUNTAMOUNTFAIL:

                    break;
                case COUNTINVERSTSUCCES:
                    Basebean result_c = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_c.isOk()) {
                        interest = JSON.parseObject(result_c.data, Interest.class);
                        if (!StringUtils.isEmpty(input_amount_edit.getText().toString().trim())) {
                            expect_income.setText("预期收益："
                                                  + ArithUtils.formatFloatNumber(interest
                                                      .getInterest()) + "元");
                        } else {
                            expect_income.setText("预期收益：");
                        }
                    } else {
                        showToast(result_c.codeDesc);
                    }
                    break;
                case COUNTINVERSTFAIL:

                    break;

                case LOOPTOCOUNTINSERT: //轮询看是否需要计算收益
                    tempNumNow = amountContent;
                    String temp = (String) msg.obj;
                    if (!StringUtils.isEmpty(tempNumNow) && Double.parseDouble(tempNumNow) != 0) {
                        if (tempNumNow.equals(temp)) {
                            if (!ArithUtils.isValidAmount(tempNumNow)) {
                                showToast("请输入有效金额");
                                break;
                            }
                            countinsert(tempNumNow.toString());
                        }
                    }
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        input_amount_edit.addTextChangedListener(new TextWatcher() {

            String aaa = "";

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                aaa = s.toString(); //edittext变化之前的内容
            }

            @Override
            public void afterTextChanged(Editable s) {
                String bbb = s.toString();//edittext变化之后的内容
                if (".".equals(s.toString())) {
                    input_amount_edit.setText("");
                    return;
                }
                if (!bbb.equals(aaa)) {
                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) > avlibe) {
                            showToast("输入金额不能大于剩余可购买本金");
                            input_amount_edit.setText(aaa);
                            return;
                        }
                    }
                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) == 0) {
                            expect_income.setText("预期收益：");
                            amountContent = s.toString();
                        } else {
                            expect_income.setText("预期收益：计算中...");
                            amountContent = s.toString();
                        }
                    } else {
                        expect_income.setText("预期收益：");
                        amountContent = s.toString();
                    }
                    String tempNumPre = amountContent;
                    Message preNumMes = Message.obtain();
                    preNumMes.obj = tempNumPre;
                    preNumMes.what = LOOPTOCOUNTINSERT;
                    handler.sendMessageDelayed(preNumMes, 1000); //发送一个延迟3秒的消息。系统收到消息后会对比文本框内容是否有变化。如果没有变化则请求预期收益接口

                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) < 100) {
                            input_amount_edit.setTextColor(DebtInverstInputAmountPage.this
                                .getResources().getColor(color.gray));
                        } else {
                            input_amount_edit.setTextColor(DebtInverstInputAmountPage.this
                                .getResources().getColor(color.gray));
                        }
                    }
                }
            }
        });

    }

    @Override
    protected void processLogic() {
        input_amount_edit.requestFocus();
        //弹出键盘
        this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        initPage();
    }

    private void initPage() {
        order = (DebtProjectdetailData) getIntent().getSerializableExtra("ORDER");

        minInvestAmount = order.getMinInvest();
        maxInvestAmount = order.getMaxInvest();
        if (minInvestAmount == 0) {
            input_amount_edit.setHint("请输入购买金额(无限额)");
        } else {
            input_amount_edit.setHint("请输入购买金额(" + ArithUtils.coverMoney(minInvestAmount + "")
                                      + "元起)");
        }
        avlibe = Double.parseDouble(order.getRemainAmount()); //剩余可买本金
        parm = getParm();
        sub_title_left_bt.setVisibility(View.VISIBLE);
        sub_title_left_bt.setImageDrawable(this.getResources().getDrawable(R.drawable.leftback));
        //根据ContractDemoMethod字段的返回是否为空，来判断协议是否显示
        if (StringUtils.isEmpty(order.getpType())) {
            sub_title_right_tv.setVisibility(View.GONE);
        } else {
            sub_title_right_tv.setVisibility(View.VISIBLE);
        }
        sub_title_right_tv.setText("协议");
        sub_title_center_tv.setText("购买金额");
        can_inverst_text.setText("剩余可买本金：" + ArithUtils.coverMoney(avlibe + "") + "元");
        getuserassert();
    }

    private void getuserassert() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.ASSETQUERY, handler, GETASSERTSUCCES, GETASSERTFAIL, false, true,
            false);
    }

    /**
     * 计算输入金额的预计收益
     * 
     * @param money
     */
    private void countinsert(String money) {
        if(allBuy){
            allBuy = false;
            return;
        }
        parm.clear();
        parm.put("bId", order.getbId());
        parm.put("amount", ArithUtils.coverMoney(money));
        getDate(parm, Constants.CALINTERESTBOND, handler, COUNTINVERSTSUCCES, COUNTINVERSTFAIL,
            false, true, false);
    }

    /**
     * 请求账户余额的预计收益，并得到对应的打折金额和垫付利息
     * 
     * @param money
     */
    private void countinsertByAccountAmount(String money) {
        allBuy = true;
        parm.clear();
        parm.put("bId", order.getbId());
        parm.put("type", "all");
        parm.put("amount", ArithUtils.coverMoney(money));
        getDate(parm, Constants.CALINTERESTBOND, handler, COUNTINVERSTBYACCOUNTAMOUNTSUCCES,
            COUNTINVERSTBYACCOUNTAMOUNTFAIL, false, true, false);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
    }

}
